<?php
namespace app\admin\controller\main;
use app\admin\model\CollectLog;
use app\common\controller\AdminController;
use app\common\model\Collect as Model;

use app\common\model\CollectCategory;
use think\App;

use think\facade\Request;
use think\facade\Session;


/**
 * @ControllerAnnotation(title="SEO推送记录")
 * Class SeoLog
 * @package app\admin\controller\main
 */
class Collect extends AdminController
{
    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $updatekey=env('key');
        if(!$updatekey){
            $this->error('请将updatekey配置在根目录的.env文件中[KEY=xxxxx]','','https://bbs.laysns.com/apps/developer/myupkey.html');
        }
        $this->model=new CollectLog();
    }
    public function index()
    {
        $key=sysconfig('key.job_key');
        $jobUrl=domain_url('/index/job/collect').'?key='.$key;

        return $this->fetch('', [
            'jobUrl'=>$jobUrl,
            'admin' => session('admin'),
        ]);
    }

    public function gather(){
        //key
        return json(getJsonData('Collect','gather',[],60*24));
    }


    public function list(){
        $data = $this->request->param();
        if ($this->request->isAjax()) {
            $where=[
                'site_name'=>$data['site_name'],
                'page'=>$data['page'],
            ];
            $result=getJsonData('Collect','list',$where,60);

            if(is_array($result)&&$result['code']==1) {
                $result['code']=0;
                $list=$result['data'];
                $uniquekeys=array_column($list,'uniquekey');
                $hasUniquekeys=(new CollectLog())->whereIn('uniquekey',$uniquekeys)->column('uniquekey');

                foreach ($list as &$v){
                    if(!empty($hasUniquekeys)&&in_array($v['uniquekey'],$hasUniquekeys)){
                        $v['collected']=1;
                    }else{
                        $v['collected']=0;
                    }
                }
                $result['data']=$list;
                return json($result);
            }else{
                $result['code']=1;
                return json($result);
            }
        }
        return $this->fetch();
    }

    public function log(){
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            $where['rule_id']=0;
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    public function category(){
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            $model=new CollectCategory();
            $count = $model
                ->where($where)
                ->count();
            $list = $model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    public function download($uniquekeys=null,$id = null,$start = null,$optstep = 0,$sitetype=null)
    {
        if($sitetype&&$sitetype!='article'){
            return fail('暂时只能采集文章板块');
        }
        //防止备份数据过程超时
        function_exists('set_time_limit') && set_time_limit(0);
        if(Request::isPost() && !empty($uniquekeys) && is_array($uniquekeys) && empty($optstep))
        {
            session::set('uniquekeys', $uniquekeys);
            session::set('sitetype', $sitetype);
            $count=count($uniquekeys);
                $speed = (floor((1/$count)*10000)/10000*100);
                $speed = sprintf("%.2f", $speed);
                $tab = array('id' => 0, 'start' => 0,'count'=>$count, 'speed'=>$speed, 'uniquekey'=>$uniquekeys[0], 'optstep'=>1);
                return json(['code' => 1, 'msg' => '初始化成功！','uniquekey'=>$tab,'uniquekeys'=>$uniquekeys]);
        }elseif (Request::isPost() && is_numeric($id) && is_numeric($start) && 1 == intval($optstep)){
            $uniquekeys = session::get('uniquekeys');
            $count=count($uniquekeys);
            $siteType = session::get('sitetype');
            $res  = (new Model())->download($uniquekeys[$id],$siteType);
            if($res===false){
                $this->error('出错！');
            } else{
                //下一个
                if(isset($uniquekeys[++$id])){
                    $speed = (floor((($id+1)/$count)*10000)/10000*100);
                    $speed = sprintf("%.2f", $speed);
                    $tab = array('id' => $id, 'start' => 0,'count'=>$count, 'speed' => $speed, 'uniquekey'=>$uniquekeys[$id], 'optstep'=>1);
                    return ['code' => 1, 'msg' => $res==1?'已下载，跳过':'下载完成！','uniquekey'=>$tab];
                } else {
                    session::set('uniquekeys', null);
                    session::set('sitename', null);
                    $this->success($res==1?'已下载，跳过':'下载完成！');
                }
            }
        }else{
            $result = ['code' => 1, 'msg' => '参数有误'];
            return $result;
        }
    }
}